package com.xrit.sunnyday.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.xrit.sunnyday.constant.MessageConstant;
import com.xrit.sunnyday.entity.PageResult;
import com.xrit.sunnyday.entity.QueryPageBean;
import com.xrit.sunnyday.entity.Result;
import com.xrit.sunnyday.pojo.Menu;
import com.xrit.sunnyday.pojo.Role;
import com.xrit.sunnyday.service.MenuService;
import com.xrit.sunnyday.service.UserService;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.User;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Set;

/**
 * 菜单管理
 */
@RestController
@RequestMapping("/menu")
public class MenuController {

    @Reference
    UserService userService;

    @Reference
    private MenuService menuService;

    /**
     * 菜单条件分页查询
     * @param
     * @return
     */
//    @PostMapping("/findPage")
//    public Result findPage(@RequestBody QueryPageBean queryPageBean){
//        // 调用服务查询所有的菜单管理
//        PageResult page = menuService.findPage(queryPageBean);
//        //封装返回的结果
//        return new Result(true,MessageConstant.QUERY_MENU_SUCCESS,page);
//    }

    @GetMapping("/getMenu")
    public Result getMenu(){
        //从SpingSercurity中获取角色id
        User user = (User) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        // 先获取用户名
        String username = user.getUsername();
        // 根据用户名查询用户信息
        com.xrit.sunnyday.pojo.User user_pojo = userService.findByUsername(username);
        // 取出角色
        Set<Role> roles = user_pojo.getRoles();

        List<Menu> menus = null;
        for (Role role : roles) {
            // 根据角色id去获取角色对应的菜单
            menus = menuService.findByRoid(role.getId());
        }
        return new Result(true, MessageConstant.GET_MENU_SUCCESS,menus);
    }
    @PostMapping("/add")
    public Result add(@RequestBody Menu menu){
        menuService.add(menu);
        return new Result(true,MessageConstant.ADD_MENU_SUCCESS);
    }

}
